package wml.clipstore.storage.clips;

import java.util.Collection;
import java.util.List;

import wml.clipstore.base.Entity;
import wml.clipstore.base.FieldValue;
import CLIPSJNI.Environment;

public class Manipulater {

	private Environment clips;

	public Manipulater(Environment clips) {
		this.clips = clips;
	}

	public boolean update(String className, String query,
			List<FieldValue> values) {
		String update = values2String(values);
		StringBuilder uq = new StringBuilder("(do-for-all-instances ((?ins ")
				.append(className).append(")) ").append(query)
				.append("(modify-instance ?ins").append(update).append("))");
		clips.eval(uq.toString());
		return true;
	}

	public boolean delete(String className, String query) {
		StringBuilder dq = new StringBuilder("(do-for-all-instances ((?ins ")
				.append(className).append(")) ").append(query)
				.append("(unmake-instance ?ins))");
		clips.eval(dq.toString());
		return true;
	}

	private String values2String(List<FieldValue> values) {
		StringBuilder update = new StringBuilder();
		for (FieldValue f : values) {
			update.append("(f_").append(f.getField()).append(" ")
					.append(this.toString(f.getValue())).append(")");
		}
		return update.toString();
	}

	private String toString(Object value) {
		if (value instanceof Entity || value instanceof Collection)
			return "(instance-address [" + value.getClass().getName() + "."
					+ value.hashCode() + "])";
		else
			return "\"" + value + "@" + value.getClass().getName() + "\"";
	}
}
